package accueil.pack;

import chemin.pack.R;
import chemin.pack.R.layout;
import chemins.pack.*;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.util.Log;
import android.view.*;
import android.widget.ListView;
import android.widget.*;
import communication.AndroidConnection;
import communication.IncomingHandler;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;


public class Login extends Activity {
    AndroidConnection conn;
    
    IncomingHandler handler;
    boolean running = true;
    Thread sendData;

    Switcher switcher;
    String assistanceType;
    
    int creditInitial = -1;
    int credit = 1;
    int penteMax = 20;
    int penteMin = -20;
    String texteCadreLegal = "";
    

    SharedPreferences preferences;
    SharedPreferences.Editor preferencesEditor;

    
    LinearLayout.LayoutParams jaugeCreditD= new LinearLayout.LayoutParams(0,LayoutParams.MATCH_PARENT,0);
    LinearLayout.LayoutParams jaugeCreditG= new LinearLayout.LayoutParams(0,LayoutParams.MATCH_PARENT,0);
    View view;
        
    String adresseMail;
    String prenom;
    String nom;
    String bluetooth;
    ViewGroup layout;
    



    @Override
    protected void onStop() {
        
        conn.close();
        super.onStop();
        
    
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exitActivity(view);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    
    @Override
	 public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
                
                preferences = getSharedPreferences("myPreferences",MODE_MULTI_PROCESS);
                preferencesEditor = preferences.edit();
                
                handler = new IncomingHandler(){
                        @Override
                        public void handleSendMsg(final String string) {
                            
                            
                            
                            sendData = new Thread(){

                                @Override
                                public void run() {

                                    while(running){
                                        Log.i("IncomingHandler", "trying to send data...");
                                        if(conn.write(string)){
                                            Log.i("IncomingHandler", "sended message to request data from computer");
                                            return;
                                        }
                                        try {
                                            Thread.sleep(1000);
                                        } catch (InterruptedException ex) {
                                            Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex);
                                            return;
                                        }
                                    }
                                }
                            };
                            sendData.start();
                        }

                        @Override
                        public void handleReset() {
                            
                            
                            conn.write("reset");
                            conn.close();
                            Log.i("restet","reset");
                        }
                        
                        @Override
                        
                        public void handleData(String substring) {
                            
                            Log.i("message du handler"," message = " + substring);
                            
                            if(substring.equals("tryToConnect"))
                            {
                                Log.i("Connection","reset -> couleur rouge");
                                changerCouleurDel("rouge");
                                bluetooth = "off";
                            }

                            
                            
                            if(substring.startsWith("preferences.max:")){
                                creditInitial = Integer.parseInt(substring.substring(16));
                                
                                if(creditInitial == -1)
                                {
                                    credit = 1;
                                    
                                }
                                else
                                {
                                    credit = creditInitial;
                                }
                                
                            }
                            
                            
                            if(substring.startsWith("preferences.penteNegative:")){
                                
                                penteMin = Integer.parseInt(substring.substring(26));
                                preferencesEditor.putInt("penteMin", penteMin);
                                
                                Log.i("PenteMin", "pente min = " + penteMin);
                            }
                            if(substring.startsWith("preferences.pentePositive:")){
                                
                                penteMax = Integer.parseInt(substring.substring(26));
                                preferencesEditor.putInt("penteMax", penteMax);
                                
                                Log.i("PenteMAX", "pente max = " + penteMax);
                        
                            }
                            if(substring.startsWith("preferences.contenuLegal:")){
                                
                                texteCadreLegal = substring.substring(25);
                                preferencesEditor.putString("texteCadreJuridique", texteCadreLegal);
                                
                            }

                        }
                        
                        @Override
                        public void handleReconnect() {

                            changerCouleurDel("verte"); 
                            bluetooth = "on";
                        }

                        @Override
                        public void handleMoveChange(String msg) {
                            
                        }
                      
                };
                

                
                
                        
                /* Set full screen view*/
	        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
	                                         WindowManager.LayoutParams.FLAG_FULLSCREEN);
	        requestWindowFeature(Window.FEATURE_NO_TITLE);

                setContentView(R.layout.login_interface);
                
                
                switcher = new Switcher(this,null,(ImageView)findViewById(R.id.switchImageView));
                layout = (ViewGroup) findViewById(R.id.switchLayout); 
                layout.addView(switcher);
              
                conn = new AndroidConnection(handler){
                    
                    @Override
                    public void initialize() {
                        handler.sendMessage(handler.obtainMessage(IncomingHandler.INCOMING_BT_MSG,"transmitData.tryToConnect"));
                        
                        
                        super.initialize();
                    }
                };
                conn.initialize();
                
                handler.sendMessage(handler.obtainMessage(IncomingHandler.SEND_MESSAGE,null));
                handler.handleSendMsg("requestPreferences");
                
	        
                initialisationText();
                
                
                
                

	    }
	 

	   public void versMenu(View v)
	    {
                 if(verificationChamps() == true)
                 {
                    preferencesEditor.commit();
                    Intent intent2 = new Intent(Login.this, Menu.class);
     
                    intent2.putExtra("typeDeChemin","monChemin");
                    intent2.putExtra("creditInitial",creditInitial);
                    intent2.putExtra("credit",credit);
                    
                    if(switcher.position.equals("up"))
                    {
                        assistanceType = "speedSensor";
                    }
                    if(switcher.position.equals("down"))
                    {
                        assistanceType = "torqueSensor";
                    }
                  
                    
                    intent2.putExtra("assistanceType",assistanceType);
                    
                    
                    CharSequence jour = ((TextView)findViewById(R.id.loginJourTextView2)).getText();
                    CharSequence mois = ((TextView)findViewById(R.id.loginMoisTextView2)).getText();
                    CharSequence annee = ((TextView)findViewById(R.id.loginAnneeTextView2)).getText();
                    
                    handler.handleSendMsg("nom:" + nom +" prenom:"+prenom + " adresseMail:"+ adresseMail + "jour" + jour + "mois" + mois + "année" + annee);
                    laverChamps();
                    
                    handler.sendMessage(handler.obtainMessage(IncomingHandler.RESET));
                    
                    startActivity(intent2);
                    finish();
                 }
	         
  
	    }
	   
	   
	   
	    public void exitActivity(View v)
	    {
	    
	        finish();

	    }
            
            public void initialisationText()
            {
                Typeface policeAltermove = Typeface.createFromAsset(getAssets(), "eurosti.ttf");
                
                ((TextView) findViewById(R.id.loginLoginTextView)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginLoginTextView)).setTextSize(40);
                
                ((TextView) findViewById(R.id.loginPrenomTextView)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginPrenomTextView)).setTextSize(23);
                
                ((TextView) findViewById(R.id.loginPrenomEditText)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginPrenomEditText)).setTextSize(23);
                
                
                ((TextView) findViewById(R.id.loginNomTextView)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginNomTextView)).setTextSize(23);
                
                ((TextView) findViewById(R.id.loginNomEditText)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginNomEditText)).setTextSize(23);
                
                ((TextView) findViewById(R.id.loginAdresseMailTextView)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginAdresseMailTextView)).setTextSize(23);
                
                ((TextView) findViewById(R.id.loginAdresseMailEditText)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginAdresseMailEditText)).setTextSize(23);
                
                ((TextView) findViewById(R.id.loginDateDeNaissanceTextView)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginDateDeNaissanceTextView)).setTextSize(23);
                
                ((TextView) findViewById(R.id.loginValiderTextView)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginValiderTextView)).setTextSize(30);
                

                
                ((TextView) findViewById(R.id.loginJourTextView1)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginJourTextView1)).setTextSize(30);
                ((TextView) findViewById(R.id.loginJourTextView2)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginJourTextView2)).setTextSize(30);
                ((TextView) findViewById(R.id.loginJourTextView3)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginJourTextView3)).setTextSize(30);
                
                ((TextView) findViewById(R.id.loginMoisTextView1)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginMoisTextView1)).setTextSize(30);
                ((TextView) findViewById(R.id.loginMoisTextView2)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginMoisTextView2)).setTextSize(30);
                ((TextView) findViewById(R.id.loginMoisTextView3)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginMoisTextView3)).setTextSize(30);


                ((TextView) findViewById(R.id.loginAnneeTextView1)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginAnneeTextView1)).setTextSize(30);
                ((TextView) findViewById(R.id.loginAnneeTextView2)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginAnneeTextView2)).setTextSize(30);
                ((TextView) findViewById(R.id.loginAnneeTextView3)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.loginAnneeTextView3)).setTextSize(30);
                
                ((TextView) findViewById(R.id.switchSpeedSensorTextView)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.switchSpeedSensorTextView)).setTextSize(20);
                ((TextView) findViewById(R.id.switchTorqueSensorTextView)).setTypeface(policeAltermove);
                ((TextView) findViewById(R.id.switchTorqueSensorTextView)).setTextSize(20);
                
                initialisationDate();
	 
            }
            
            public void initialisationDate()
            {
                String[] liste;
                ViewGroup layout;
                Scroll moisScroll,anneeScroll,jourScroll;
                int i;
                
                liste = new String[31];
                for(i=1;i<32;i++)
                {
                    liste[i-1]= Integer.toString(i);
                }
                jourScroll = new Scroll(this, null,(TextView)findViewById(R.id.loginJourTextView1),(TextView)findViewById(R.id.loginJourTextView2),(TextView)findViewById(R.id.loginJourTextView3),liste);
                layout = (ViewGroup) findViewById(R.id.loginJourLayout); 
                layout.addView(jourScroll);
                
                
                liste = new String[12];

                liste[0] = "Janvier";
                liste[1] = "Fevrier";
                liste[2] = "Mars";
                liste[3] = "Avril";
                liste[4] = "Mai";
                liste[5] = "Juin";
                liste[6] = "Juillet";
                liste[7] = "Aout";
                liste[8] = "Sept.";
                liste[9] = "Octobre";
                liste[10] = "Nov.";
                liste[11] = "Decembre";
                
                moisScroll = new Scroll(this, null,(TextView)findViewById(R.id.loginMoisTextView1),(TextView)findViewById(R.id.loginMoisTextView2),(TextView)findViewById(R.id.loginMoisTextView3),liste);
                layout = (ViewGroup) findViewById(R.id.loginMoisLayout); 
                layout.addView(moisScroll);
                
                liste = new String[112];
                for(i=0;i<112;i++)
                {
                    liste[i]= Integer.toString(i+1900);
                }
                anneeScroll = new Scroll(this, null,(TextView)findViewById(R.id.loginAnneeTextView1),(TextView)findViewById(R.id.loginAnneeTextView2),(TextView)findViewById(R.id.loginAnneeTextView3),liste);
                layout = (ViewGroup) findViewById(R.id.loginAnneeLayout); 
                layout.addView(anneeScroll);
                
            }
            

            
            
            public boolean verificationChamps()
            {
                nom = ((EditText) findViewById(R.id.loginNomEditText)).getText().toString();
                prenom = ((EditText) findViewById(R.id.loginPrenomEditText)).getText().toString();
                adresseMail = ((EditText) findViewById(R.id.loginAdresseMailEditText)).getText().toString();
                if(bluetooth.equals("on"))
                {
                    if(!nom.equals(""))
                    {
                        if(!prenom.equals(""))
                        {
                            if(verificationAdresseMail((CharSequence)adresseMail) == true)
                            {
                                return true;
                            }
                        } 
                    }
                }
                return false;
            }
            
            
            
            public final boolean verificationAdresseMail(CharSequence target){
                try{
                        return android.util.Patterns.EMAIL_ADDRESS.matcher(target).matches();
                }
                catch(NullPointerException exception){
                        return false;
                }
            }
            
            public void laverChamps()
            {
                ((EditText) findViewById(R.id.loginNomEditText)).setText("");
                ((EditText) findViewById(R.id.loginPrenomEditText)).setText("");
                ((EditText) findViewById(R.id.loginAdresseMailEditText)).setText("");
            }
            
            public void changerCouleurDel(String couleur)
            {
                if(couleur.equals("verte"))
                {
                    ((ImageView)findViewById(R.id.menuLedImageView)).setImageResource(R.drawable.led_verte);
                    Log.i("couleur"," passe en vert");
                }
                if(couleur.equals("rouge"))
                {
                    ((ImageView)findViewById(R.id.menuLedImageView)).setImageResource(R.drawable.led_rouge);
                    Log.i("couleur"," passe en rouge");
                }
                
            }

}